import subsystem from "./data.js";
import router from "@/router/index.js";
import { frameInRoutes } from "@/router/routes.js";
import { resetRouter } from "@/router/index.js";
import subsystemRouter from "@/router/subsystem.js";
import subsystemMenu from "@/menu/index.js";
import { getFrameInRoutes } from "@/libs/util.subsystem.js";


const Verification = k =>!subsystemRouter.hasOwnProperty(k) || subsystemRouter[k].length ===0 || !subsystemMenu.hasOwnProperty(k) || subsystemMenu[k].length ===0;


export default {
  namespaced: true,
  state: {
    system: subsystem,
    active: localStorage.getItem("subsystemActiveKey")
  },
  getters: {
    subsystem: state => {
      return state.system[state.active];
    }
  },
  actions: {
    /**
     * @description 初始化子系统
     * @param {Object} state state
     * @param commit
     * @param dispatch
     * @param subsystemKey
     */
    async initSubsystem({ state, commit, dispatch }, subsystemKey) {
      if (Verification(subsystemKey)) {
        alert("系统正在开发中，敬请期待。");
        return;
      }
      state.active = subsystemKey;
      localStorage.setItem("subsystemActiveKey", subsystemKey);
      await dispatch("init", subsystemKey);
      commit("d2admin/page/init", [subsystemRouter[subsystemKey][0]], {
        root: true
      });
      router.replace(subsystemMenu[subsystemKey][0].path);
    },
    /**
     * @description 重新加载子系统
     * @param {Object} state state
     * @param dispatch
     */
    async reloadSubsystem({ state, dispatch }) {
      let k = localStorage.getItem("subsystemActiveKey");
      if (!k) {
        router.replace("/dashboard");
        return;
      }
      state.active = k;
      await dispatch("init", k);
    },
    /**
     * 添加子系统路由
     * @param {Object} context
     * @param subsystemKey
     */
    async init({ state, commit, dispatch }, subsystemKey) {
      resetRouter(); //将之前其他系统的路由重置掉
      router.addRoutes(subsystemRouter[subsystemKey]);
      // 处理路由 得到每一级的路由设置
      commit(
        "d2admin/page/init",
        [...frameInRoutes, ...getFrameInRoutes(subsystemRouter[subsystemKey])],
        { root: true }
      ); //要改
      // 设置顶栏菜单
      commit("d2admin/menu/headerSet", subsystemMenu[subsystemKey], {
        root: true
      });
      // 设置侧边栏菜单
      commit("d2admin/menu/asideSet", subsystemMenu[subsystemKey], {
        root: true
      });
      // 初始化菜单搜索功能
      commit("d2admin/search/init", subsystemMenu[subsystemKey], {
        root: true
      });
    }
  }
};
